﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Buz.Base.Enums;
using ST.Common.Util.Security;
using Microsoft.Data.SqlClient;
using ST.Buz.Base.ViewModel;
using System.Data;
using System.Reflection;
using System.Text;
using NPOI.SS.UserModel;
using ST.Common.Util.Office;
using System.IO;
using NPOI.SS.Formula.Functions;

namespace ST.Buz.Service
{
	public partial interface IServiceSysOrganization
	{
		/// <summary>
		/// 获取单位详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		Sys_Organization Get(int id, UserSession sessionCurrent);

		/// <summary>
		/// 生成单位编码
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		string GenCode(string areaCode, UserSession sessionCurrent);

		/// <summary>
		/// 通过编号查询单位信息
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		Sys_Organization GetByCode(string code);

		/// <summary>
		/// 审核
		/// </summary>
		/// <param name="id"></param>
		/// <param name="state"></param>
		/// <returns></returns>
		bool Audit(int id, int state, string remark, UserSession sessionCurrent);

		/// <summary>
		/// 删除单位
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent);

		/// <summary>
		/// 批量删除单位
		/// </summary>
		/// <returns></returns>
		bool BatchDelete(int[] ids, UserSession sessionCurrent);

		/// <summary>
		/// 检验登录账号是否可用
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool ValidateCode(int id, string code, UserSession sessionCurrent);

		/// <summary>
		/// 分页列表
		/// </summary>
		PageData GetPageList(VMS_Sys_Organization searchModel);

		/// <summary>
		/// 分页列表
		/// </summary>
		PageData GetDetailPageList(VMS_Sys_Organization searchModel);

		/// <summary>
		/// 新增或修改保存
		/// </summary>
		int AddOrUpdate(Sys_Organization model, UserSession sessionCurrent);

		/// <summary>
		/// 批量导入
		/// </summary>
		bool BatchImport(string filepath, UserSession sessionCurrent);

		/// <summary>
		/// 获取下级单位列表
		/// </summary>
		PageData GetChildList(int id, UserSession sessionCurrent);

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的ZTree格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		List<ZTreeItem> GetZTreeData(int id);
	}

	public partial class ServiceSysOrganization
	{
		private readonly IServiceSysArea serviceSysArea;
		private readonly IServiceSysLog serviceSysLog;
		private readonly IServiceSysTableLog serviceSysTableLog;

		public ServiceSysOrganization(BuzContext ctx,
			IServiceSysArea _serviceSysArea,
			IServiceSysLog _serviceSysLog,
			IServiceSysTableLog _serviceSysTableLog,
			ILogger<ServiceSysOrganization> log)
		{
			serviceSysArea = _serviceSysArea;
			serviceSysLog = _serviceSysLog;
			serviceSysTableLog = _serviceSysTableLog;

			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 获取单位详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public Sys_Organization Get(int id, UserSession sessionCurrent)
		{
			Sys_Organization model = null;
			try
			{
				model = context.SysOrganization.SingleOrDefault(m => m.ID == id);
				if (model == null)
				{
					throw new BuzException("参数有误");
				}
				//var query = from u in context.SysOrganization
				//			where u.ID == id
				//			join d in context.SysArea on u.AreaID equals d.ID into udtmp
				//			from ud in udtmp.DefaultIfEmpty()
				//			select new
				//			{
				//				Model = u,
				//				Area = ud
				//			};
				//var results = query.ToArray();
				//if (results == null || results.Length == 0)
				//{
				//	throw new BuzException("参数有误");
				//}
				//model = results[0].Model;
				if (model.AreaID > 0)
				{
					model.AreaName = serviceSysArea.GetTopLevelName(model.AreaID, sessionCurrent);
				}
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return model;
		}

		/// <summary>
		/// 生成单位编码
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public string GenCode(string areaCode, UserSession sessionCurrent)
		{
			try
			{
				DateTime dtNow = DateTime.Now;
				string prefix = !string.IsNullOrEmpty(areaCode) ? areaCode : "000000";
				string maxSNo = context.SysOrganization.Where(m => EF.Functions.Like(m.Code, prefix + "%")).Max(m => m.Code);
				int maxNo = 0;
				if (!string.IsNullOrEmpty(maxSNo))
				{
					int.TryParse(maxSNo.Substring(prefix.Length), out maxNo);
				}

				return prefix + (maxNo + 1).ToString().PadLeft(4, '0');
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "生成单位编码出错");
				throw new BuzException("生成单位编码失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 通过编号查询单位信息
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public Sys_Organization GetByCode(string code)
		{
			Sys_Organization model = null;
			try
			{
				if (string.IsNullOrEmpty(code))
				{
					throw new BuzException("单位编码不能为空");
				}
				model = context.SysOrganization.SingleOrDefault(m => m.Code == code);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return model;
		}

		/// <summary>
		/// 审核
		/// </summary>
		/// <param name="id"></param>
		/// <param name="state"></param>
		/// <returns></returns>
		public bool Audit(int id, int state, string remark, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				if (logger.IsEnabled(LogLevel.Debug))
				{
					logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				}
				//if (state != (int)OrganizationState.正常 && state != (int)OrganizationState.未授权)
				//{
				//	throw new BuzException("审核状态信息有误");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				Sys_Organization user = null;
				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						user = context.SysOrganization.SingleOrDefault(m => m.ID == id);
						if (user == null)
						{
							throw new BuzException("未找到相关记录");
						}
						user.StateNow = state;
						context.SaveChanges();
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "审核信息出错");
				throw new BuzException("审核信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 删除具体操作
		/// </summary>
		/// <param name="id"></param>
		/// <param name="ip"></param>
		/// <param name="dtNow"></param>
		/// <param name="sessionCurrent"></param>
		protected void DeleteWithinTrans(int id, string ip, DateTime dtNow, UserSession sessionCurrent)
		{
			var modelOld = Get(id, true);
			if (context.SysUser.Any(m => m.OrgID == id))
			{
				throw new BuzException("该单位下有员工，不能删除");
			}
			Delete(modelOld);

			serviceSysLog.Add(sessionCurrent, ip, $"删除单位{modelOld.Name}[{modelOld.Code}]信息，原信息：", modelOld, dtNow);
		}

		/// <summary>
		/// 删除单位
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						DeleteWithinTrans(id, ip, dtNow, sessionCurrent);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除单位出错");
				throw new BuzException("删除单位失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 批量删除单位
		/// </summary>
		/// <returns></returns>
		public bool BatchDelete(int[] ids, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				if (ids == null || ids.Length == 0)
				{
					throw new BuzException("参数不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						foreach (int id in ids)
						{
							DeleteWithinTrans(id, ip, dtNow, sessionCurrent);
						}
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "批量删除单位出错");
				throw new BuzException("批量删除单位失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 检验登录账号是否可用
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool ValidateCode(int id, string code, UserSession sessionCurrent)
		{
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (string.IsNullOrEmpty(code))
				{
					throw new BuzException("登录账号不能为空");
				}
				if (id == 0)
				{
					return !context.SysOrganization.Any(m => m.Code == code);
				}
				var lst = context.SysOrganization.Where(m => m.Code == code).AsNoTracking().ToList();
				if (lst.Count == 0)
				{
					return true;
				}
				foreach (var i in lst)
				{
					if (i.ID != id)
					{
						return false;
					}
				}

				return true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "检验登录账号是否可用出错");
				throw new BuzException("检验登录账号是否可用失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_Sys_Organization searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();

				var query = from u in context.SysOrganization
							join d in context.SysArea on u.AreaID equals d.ID into udtmp
							from ud in udtmp.DefaultIfEmpty()
							select new
							{
								u.PID,
								ID = u.ID,
								Code = u.Code,
								Province = u.Province,
								City = u.City,
								District = u.District,
								Town = u.Town,
								DetailAddress = u.DetailAddress,
								u.EMail,
								u.Fax,
								u.Lat,
								u.Lng,
								PYCode = u.PYCode,
								u.ZipCode,
								u.Phone,
								u.LegalMan,
								u.LegalManIDCardNo,
								u.LegalManPhone,
								u.ChargeMan,
								u.ChargeManIDCardNo,
								u.ChargeManPhone,
								Name = u.Name,
								u.AreaID,
								u.AddDate,
								u.AddManName,
								AreaName = ud.Name,
								StateNow = u.StateNow
							};
				if (!string.IsNullOrWhiteSpace(searchModel.name))
				{
					query = query.Where(m => EF.Functions.Like(m.Name, "%" + searchModel.name + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.code))
				{
					query = query.Where(m => m.Code == searchModel.code);
				}
				if (!string.IsNullOrEmpty(searchModel.chargeman))
				{
					query = query.Where(m => EF.Functions.Like(m.ChargeMan, "%" + searchModel.chargeman + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.chargemanphone))
				{
					query = query.Where(m => EF.Functions.Like(m.ChargeManPhone, "%" + searchModel.chargemanphone + "%"));
				}
				if (searchModel.pid.HasValue)
				{
					query = query.Where(m => m.PID == searchModel.pid);
				}
				if (searchModel.areaid.HasValue)
				{
					var children = context.ExecuteReader<TreeIdentity>(
						"sp_sys_get_tree_children",
						new SqlParameter[] { new SqlParameter("@id", searchModel.areaid.Value), new SqlParameter("@table_name", "Sys_Area") }
					);
					if (children.Count > 0)
					{
						List<int> lstTree = new List<int>();
						foreach (var c in children)
						{
							lstTree.Add(c.ID);
						}
						query = query.Where(m => lstTree.Contains(m.AreaID));
					}
					else
					{
						query = query.Where(m => m.AreaID == searchModel.areaid.Value);
					}
				}
				if (searchModel.state.HasValue)
				{
					query = query.Where(m => m.StateNow == searchModel.state.Value);
				}

				switch (searchModel.sortby)
				{
					case "Code":
						////数据库分页，不支持多表
						//query = query.OrderByDescending(e => EF.Property<object>(e, sortOrder));
						////内存分页
						////query = query.OrderByDescending(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Code) : query.OrderByDescending(e => e.Code);
						break;
					case "AreaName":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.AreaName) : query.OrderByDescending(e => e.AreaName);
						break;
					case "Name":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
						break;
					case "StateNow":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.StateNow) : query.OrderByDescending(e => e.StateNow);
						break;
					default:
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetDetailPageList(VMS_Sys_Organization searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();

				var query = 
							from u in context.SysOrganization
							join p in context.SysOrganization on u.PID equals p.ID into uptmp
							from up in uptmp.DefaultIfEmpty()
							join d in context.SysArea on u.AreaID equals d.ID into udtmp
							from ud in udtmp.DefaultIfEmpty()
							select new
							{
								u.Type,
								u.PartnerID,
								u.PartnerName,
								u.PID,
								PName = up.Name,
								ID = u.ID,
								Code = u.Code,
								Province = u.Province,
								City = u.City,
								District = u.District,
								Town = u.Town,
								DetailAddress = u.DetailAddress,
								u.EMail,
								u.Fax,
								u.Lat,
								u.Lng,
								PYCode = u.PYCode,
								u.ZipCode,
								u.Phone,
								u.LegalMan,
								u.LegalManIDCardNo,
								u.LegalManPhone,
								u.ChargeMan,
								u.ChargeManIDCardNo,
								u.ChargeManPhone,
								Name = u.Name,
								u.AreaID,
								u.AddDate,
								u.AddManName,
								AreaName = ud.Name,
								StateNow = u.StateNow
							};
				if (!string.IsNullOrWhiteSpace(searchModel.name))
				{
					query = query.Where(m => EF.Functions.Like(m.Name, "%" + searchModel.name + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.code))
				{
					query = query.Where(m => m.Code == searchModel.code);
				}
				if (!string.IsNullOrEmpty(searchModel.chargeman))
				{
					query = query.Where(m => EF.Functions.Like(m.ChargeMan, "%" + searchModel.chargeman + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.chargemanphone))
				{
					query = query.Where(m => EF.Functions.Like(m.ChargeManPhone, "%" + searchModel.chargemanphone + "%"));
				}
				if (searchModel.pid.HasValue)
				{
					query = query.Where(m => m.PID == searchModel.pid);
				}
				if (searchModel.areaid.HasValue)
				{
					var children = context.ExecuteReader<TreeIdentity>(
						"sp_sys_get_tree_children",
						new SqlParameter[] { new SqlParameter("@id", searchModel.areaid.Value), new SqlParameter("@table_name", "Sys_Area") }
					);
					if (children.Count > 0)
					{
						List<int> lstTree = new List<int>();
						foreach (var c in children)
						{
							lstTree.Add(c.ID);
						}
						query = query.Where(m => lstTree.Contains(m.AreaID));
					}
					else
					{
						query = query.Where(m => m.AreaID == searchModel.areaid.Value);
					}
				}
				if (searchModel.type.HasValue && searchModel.type.Value != 0)
				{
					query = query.Where(m => m.Type == searchModel.type.Value);
				}
				if (searchModel.state.HasValue)
				{
					query = query.Where(m => m.StateNow == searchModel.state.Value);
				}

				switch (searchModel.sortby)
				{
					case "Code":
						////数据库分页，不支持多表
						//query = query.OrderByDescending(e => EF.Property<object>(e, sortOrder));
						////内存分页
						////query = query.OrderByDescending(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Code) : query.OrderByDescending(e => e.Code);
						break;
					case "AreaName":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.AreaName) : query.OrderByDescending(e => e.AreaName);
						break;
					case "Name":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
						break;
					case "StateNow":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.StateNow) : query.OrderByDescending(e => e.StateNow);
						break;
					default:
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 新增或修改保存
		/// </summary>
		public int AddOrUpdate(Sys_Organization model, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (model == null)
				{
					throw new BuzException("参数不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						if (model.ID > 0)
						{
							if (context.SysOrganization.Any(m => m.Code == model.Code && m.ID != model.ID))
							{
								throw new BuzException("单位编码重复");
							}
							Update(model);

							//serviceSysTableLog.Add(sessionCurrent, TableCode.Sys_Organization, model.ID, ip, "修改单位信息，新信息如下：", model, dtNow, true);
						}
						else
						{
							if (context.SysOrganization.Any(m => m.Code == model.Code))
							{
								throw new BuzException("单位编码重复");
							}
							model.AddDate = dtNow;
							model.AddManID = sessionCurrent.UserID;
							model.AddManName = sessionCurrent.UserName;
							model.StateNow = (int)OrganizationState.正常;
							Add(model);
						}

						#endregion

						trans.Commit();

						return model.ID;
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public bool BatchImport(string filepath, UserSession sessionCurrent)
		{
			try
			{
				var lst = ParseExcel(filepath);

				BatchImport(lst, sessionCurrent);

				return true;
			}
			catch (AuthException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException("Excel导入失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), ex);
			}
		}

		protected List<Sys_Organization> GetTree(int id)
		{
			SqlParameter[] parameters = new SqlParameter[]{
					new SqlParameter("@org_id", id),
					new SqlParameter("@errcode",System.Data.SqlDbType.Int),
					new SqlParameter("@errmsg",System.Data.SqlDbType.NVarChar,200)
				};
			parameters[parameters.Length - 2].Direction = System.Data.ParameterDirection.Output;
			parameters[parameters.Length - 1].Direction = System.Data.ParameterDirection.Output;
			var result = context.SysOrganization.FromSqlRaw("sp_sys_organization_tree @org_id,@errcode output,@errmsg output", parameters).ToList();
			if ((int)parameters[parameters.Length - 2].Value != 0)
			{
				throw new BuzException(Convert.ToString(parameters[parameters.Length - 1].Value));
			}
			return result;
		}

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的简单格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<SimpleTreeItem> GetSimpleTreeData(int id)
		{
			try
			{
				var treeData = GetTree(id);
				var result = new List<SimpleTreeItem>();
				foreach (var q in treeData)
				{
					result.Add(new SimpleTreeItem()
					{
						pId = q.PID.ToString(),
						id = q.ID.ToString(),
						key = q.ID.ToString(),
						value = q.ID.ToString(),
						title = q.Name,
					});
				}
				return result;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}

		/// <summary>
		/// 获取全部的树节点数据的简单格式
		/// </summary>
		/// <returns></returns>
		public List<SimpleTreeItem> GetSimpleTreeData()
		{
			var query = from m in context.SysOrganization
						select new SimpleTreeItem()
						{
							pId = m.PID.ToString(),
							id = m.ID.ToString(),
							key = m.ID.ToString(),
							value = m.ID.ToString(),
							title = m.Name,
						};
			return query.ToList();
		}

		/// <summary>
		/// 获取指定及其所有下级的树节点数据的ZTree格式
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<ZTreeItem> GetZTreeData(int id)
		{
			try
			{
				var result = new List<ZTreeItem>();
				result.Add(new ZTreeItem()
				{
					id = "0",
					pId = "-1",
					name = "全部",
					isParent = true,
					open = true
				});
				var treeData = GetTree(id);
				foreach (var q in treeData)
				{
					result.Add(new ZTreeItem()
					{
						pId = q.PID.ToString(),
						id = q.ID.ToString(),
						name = q.Name,
						//isParent = q.Children > 0,
						open = true
					});
				}
				return result;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}

	}
}